const { Cart, Material, User, Download } = require('../models');
const { Op } = require('sequelize');
const crypto = require('crypto');

// 获取购物车列表
exports.getCartItems = async (req, res) => {
  try {
    const cartItems = await Cart.findAll({
      where: { 
        userId: req.user.id,
        status: 'pending'  // 只获取未结算的项目
      },
      include: [{
        model: Material,
        as: 'material',
        attributes: ['id', 'title', 'price', 'noWatermarkPrice', 'thumbnailUrl']
      }],
      order: [['createdAt', 'DESC']]
    });
    res.json({ success: true, data: cartItems });
  } catch (error) {
    console.error('获取购物车失败:', error);
    res.status(500).json({ success: false, message: '获取购物车失败' });
  }
};

// 添加到购物车
exports.addToCart = async (req, res) => {
  try {
    const { materialId, isWatermark, quantity = 1 } = req.body;
    
    const material = await Material.findByPk(materialId);
    if (!material) {
      return res.status(404).json({ 
        success: false, 
        message: '素材不存在' 
      });
    }

    // 检查是否已存在相同的未结算项目
    const existingItem = await Cart.findOne({
      where: {
        userId: req.user.id,
        materialId,
        status: 'pending'
      }
    });

    let cartItem;
    if (existingItem) {
      // 如果已存在，更新数量和水印选项
      cartItem = await existingItem.update({
        quantity: quantity,
        isWatermark: Boolean(isWatermark),
        expiresAt: new Date(Date.now() + 7 * 24 * 3600 * 1000)
      });
    } else {
      // 如果不存在，创建新项目
      cartItem = await Cart.create({
        userId: req.user.id,
        materialId,
        quantity,
        isWatermark: Boolean(isWatermark),
        status: 'pending',
        expiresAt: new Date(Date.now() + 7 * 24 * 3600 * 1000)
      });
    }

    // 获取完整的购物车项信息，包括关联的素材信息
    const fullCartItem = await Cart.findByPk(cartItem.id, {
      include: [{
        model: Material,
        as: 'material',
        attributes: ['id', 'title', 'price', 'noWatermarkPrice', 'thumbnailUrl']
      }]
    });

    res.json({ success: true, data: fullCartItem });
  } catch (error) {
    console.error('添加购物车失败:', error);
    res.status(500).json({ success: false, message: '添加购物车失败' });
  }
};

// 从购物车移除
exports.removeFromCart = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 查找购物车项
    const cartItem = await Cart.findOne({
      where: {
        id,
        userId: req.user.id,
        status: 'pending' // 只能移除未结算的项目
      }
    });
    
    if (!cartItem) {
      return res.status(404).json({
        success: false,
        message: '购物车项不存在、已结算或不属于当前用户'
      });
    }

    // 更新状态为已取消而不是直接删除
    await cartItem.update({
      status: 'cancelled',
      expiresAt: new Date() // 立即过期
    });

    res.json({ 
      success: true,
      message: '已从购物车移除'
    });
  } catch (error) {
    console.error('移除购物车失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '移除购物车失败',
      error: error.message 
    });
  }
};

// 结算购物车
exports.checkout = async (req, res) => {
  try {
    const { cartItemIds } = req.body;

    // 获取购物车项
    const cartItems = await Cart.findAll({
      where: {
        id: cartItemIds,
        userId: req.user.id,
        status: 'pending',
        expiresAt: { [Op.gt]: new Date() }
      },
      include: [{
        model: Material,
        as: 'material',
        attributes: ['id', 'title', 'price', 'noWatermarkPrice']
      }]
    });

    if (cartItems.length === 0) {
      return res.status(400).json({
        success: false,
        message: '购物车中没有有效商品'
      });
    }

    // 计算总价
    let totalCost = 0;
    const downloads = [];
    
    for (const item of cartItems) {
      const itemCost = item.isWatermark 
        ? item.material.price * item.quantity
        : (item.material.price + item.material.noWatermarkPrice) * item.quantity;
      
      totalCost += itemCost;

      downloads.push({
        materialId: item.materialId,
        isWatermark: item.isWatermark,
        quantity: item.quantity,
        cost: itemCost
      });
    }

    // 检查用户余额
    const user = await User.findByPk(req.user.id);
    if (user.virtualCoins < totalCost) {
      return res.status(400).json({
        success: false,
        message: '虚拟币余额不足',
        required: totalCost,
        available: user.virtualCoins
      });
    }

    // 扣减虚拟币
    await user.decrement('virtualCoins', { by: totalCost });

    // 创建下载记录
    const downloadPromises = cartItems.map(item => {
      return Download.create({
        userId: req.user.id,
        materialId: item.materialId,
        isWatermark: item.isWatermark,
        quantity: item.quantity,
        coinsSpent: item.isWatermark 
          ? item.material.price * item.quantity
          : (item.material.price + item.material.noWatermarkPrice) * item.quantity,
        ipAddress: req.ip
      });
    });

    // 更新资料下载次数
    const materialUpdatePromises = cartItems.map(item => {
      return item.material.increment('downloads', { by: item.quantity });
    });

    // 更新购物车项状态为已完成
    const updateCartStatusPromises = cartItems.map(item => {
      return item.update({ 
        status: 'completed',
        expiresAt: new Date() // 立即过期
      });
    });

    await Promise.all([
      ...downloadPromises,
      ...materialUpdatePromises,
      ...updateCartStatusPromises
    ]);

    // 生成下载链接
    const downloadLinks = await generateDownloadLinks(cartItems);

    res.json({
      success: true,
      data: {
        downloads,
        totalCost,
        remainingCoins: user.virtualCoins - totalCost,
        downloadLinks
      }
    });
  } catch (error) {
    console.error('结算失败:', error)
    res.status(500).json({
      success: false,
      message: '结算失败'
    })
  }
}

// 生成下载链接
async function generateDownloadLinks(cartItems) {
  const links = []
  
  for (const item of cartItems) {
    const token = crypto.randomBytes(16).toString('hex')
    const expiresAt = new Date(Date.now() + 24 * 3600 * 1000) // 24小时后过期
    
    // 实际项目中应该存储到数据库
    links.push({
      materialId: item.materialId,
      url: `/api/download/${item.materialId}?token=${token}`,
      expiresAt
    })
  }
  
  return links
}

// 检查购物车状态
exports.checkStatus = async (req, res) => {
  try {
    // 只检查购物车表是否存在且可访问，不需要查询具体数据
    await Cart.findOne({
      attributes: ['id'],
      limit: 1
    });

    res.json({
      success: true,
      data: {
        available: true,
        requireLogin: true, // 告诉前端需要登录才能使用购物车
        message: '购物车功能正常'
      }
    });
  } catch (error) {
    console.error('检查购物车状态失败:', error);
    res.json({
      success: true,
      data: {
        available: false,
        requireLogin: false,
        message: '购物车功能暂不可用'
      }
    });
  }
};

// 清空购物车
exports.clearCart = async (req, res) => {
  try {
    // 获取当前用户的所有未结算购物车项
    const pendingItems = await Cart.findAll({
      where: {
        userId: req.user.id,
        status: 'pending'
      }
    });

    if (pendingItems.length === 0) {
      return res.json({
        success: true,
        message: '购物车已经是空的',
        data: { itemsRemoved: 0 }
      });
    }

    // 批量更新状态为已取消
    const result = await Cart.update({
      status: 'cancelled',
      expiresAt: new Date()
    }, {
      where: {
        userId: req.user.id,
        status: 'pending'
      }
    });

    res.json({
      success: true,
      message: `已清空${pendingItems.length}个购物车项`,
      data: {
        itemsRemoved: pendingItems.length,
        items: pendingItems.map(item => ({
          id: item.id,
          materialId: item.materialId
        }))
      }
    });
  } catch (error) {
    console.error('清空购物车失败:', error);
    res.status(500).json({
      success: false,
      message: '清空购物车失败',
      error: error.message
    });
  }
};